package com.xyzwps.server.paimon.ui

import com.xyzwps.server.paimon.app.ContextUser
import com.xyzwps.server.paimon.common.ReqCtx
import com.xyzwps.server.paimon.common.TokenGetter
import com.xyzwps.server.paimon.model.service.UserDomainService
import com.xyzwps.server.paimon.model.service.UserSessionDomainService
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.jetbrains.exposed.v1.jdbc.transactions.transaction
import org.springframework.lang.NonNull
import org.springframework.stereotype.Component
import org.springframework.web.servlet.HandlerInterceptor

@Component
class MvcAuthInterceptor(
    private val userDomainService: UserDomainService,
    private val sessionService: UserSessionDomainService
) : HandlerInterceptor {

    override fun preHandle(
        @NonNull req: HttpServletRequest,
        @NonNull res: HttpServletResponse,
        @NonNull handler: Any
    ): Boolean {
        val token = TokenGetter(req).token
        if (token != null) {
            transaction {
                sessionService.getSession(token)?.let { session ->
                    userDomainService.getById(session.userId)?.let { user ->
                        req.setAttribute(ReqCtx.USER, ContextUser(user))
                        req.setAttribute(ReqCtx.SESSION, session)
                        req.setAttribute(ReqCtx.TOKEN, token)
                    }
                }
            }
        }

        return true
    }
}
